<template>
  <div class="box">
    <header class="header">
      <van-nav-bar title="登录" left-arrow @click-left="$router.back()" />
    </header>
    <div class="content">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="username"
            name="username"
            label
            placeholder="手机号或邮箱"
            :rules="[{ required: true, message: '手机号或邮箱' }]"
          />
          <van-field
            v-model="password"
            type="password"
            name="password"
            label
            placeholder="登录密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">登录</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>
<script setup>
import { ref } from "vue";
import { showSuccessToast, showFailToast } from "vant";
import request from "@/utils/request.js";
import md5 from "blueimp-md5";
import { useRouter } from 'vue-router'
const router = useRouter()
const username = ref("");
const password = ref("");
const onSubmit = values => {
  console.log("submit", values);
  request
    .post("/login", {
      username: values.username,
      password: md5(values.password)
    })
    .then(res => {
      if (res.data.code == 200) {
        //提示
        showSuccessToast(res.data.message);
        //存储token
        localStorage.setItem('token',res.data.token)
        localStorage.setItem('username',username.value)
        //跳转到我的页面
        router.push('/user')
      }
      else
      {
        showFailToast(res.data.message);
      }
    });
};
</script>